package com.woniu.communitymanagement.util;

import java.sql.*;

/**
 * JDBC工具类
 */
public class BaseDAO {

	// 数据库的连接url
	private String url = "jdbc:mysql://127.0.0.1:3306/community?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
	// 用户名
	private String user = "root";
	// 密码
	private String password = "root";
	// 驱动串
	private String className = "com.mysql.cj.jdbc.Driver";
	private Connection connection = null;
	private PreparedStatement pst;
	private ResultSet rs;

	// 1、建立连接，获取Connection对象
	public Connection getConnection() {
		if(this.connection == null) {
			try {
				Class.forName(className);
				connection = DriverManager.getConnection(url, user, password);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return connection;
	}

	// 2、获取PreparedStatement对象
	public PreparedStatement getPreparedStatement(String sql) {
		if(this.pst == null) {
			try {
				this.pst = getConnection().prepareStatement(sql);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return this.pst;
	}

	// 3、执行sql--executeUpdate
	public int executeUpdate(String sql) {
		int count = 0;
		try {
			count = getPreparedStatement(sql).executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeAll();
		}
		return count;
	}

	// 4、执行sql--executeQuery
	public ResultSet executeQuery(String sql) {
		try {
			rs = getPreparedStatement(sql).executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	// 5、释放资源
	public void closeAll() {
		try {
			if(this.rs != null) {
				this.rs.close();
				this.rs = null;
			}
			if(this.pst != null) {
				this.pst.close();
				this.pst = null;
			}
			if(this.connection != null) {
				this.connection.close();
				this.connection = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
